package com.rljk.controller.app;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.zxing.WriterException;
import com.rljk.common.controller.BaseController;
import com.rljk.common.result.Result;
import com.rljk.domain.common.PageData;
import com.rljk.redis.RedisService;
import com.rljk.utils.ZXingCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.commons.CommonsMultipartFile;


/**
 * Author:   YASUO
 * Date:     2018/8/10 16:53
 * Description:
 */

@RequestMapping("/html")
@Controller
@Slf4j
public class HtmlInController extends BaseController {

    @Autowired
    RedisService redisService;


    /**
    * 通过流的方式上传文件
    * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
    */
    @RequestMapping("fileUpload")
    public String  fileUpload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request,
                              ModelMap model) throws IOException {


        //用来检测程序运行时间
        long  startTime=System.currentTimeMillis();
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
        System.out.println("fileName："+fileName);

        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        file.transferTo(targetFile);

        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);


        long  endTime=System.currentTimeMillis();
        System.out.println("方法一的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return "/result";
    }


    @RequestMapping("fileUploadLogo")
    @ResponseBody
    public String  fileUploadLogo(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request,
                                  ModelMap model) throws IOException {


        //用来检测程序运行时间
        long  startTime=System.currentTimeMillis();
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
        System.out.println("fileName："+fileName);

        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        file.transferTo(targetFile);

        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);


        long  endTime=System.currentTimeMillis();
        System.out.println("方法一的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return "result";
    }

    /**
     * APP 合成二维码生成
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("synthesisQRCode")
    @ResponseBody
    public Object  SynthesisQRCode(HttpServletRequest request,
                                       @RequestParam(value="file",required=false) CommonsMultipartFile logoFile,
                                       @RequestParam(value="ios_url",required=true) String ios_url,
                                       @RequestParam(value="android_url",required=true) String android_url
                                   ) throws IOException {

        log.info("SynthesisQRCode - {}", "开始了");
        log.info("path - {}", request.getSession().getServletContext().getRealPath("/"));

        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getContextPath()).append("/").toString();
        log.info("tempContextUrl - {}", tempContextUrl);

        String key_id = UuidUtil.generateShortUuid();
        PageData pd = new PageData();
        pd.put("",android_url);
        pd.put("",ios_url);
        pd.put("",key_id);
        //int intInsert = qRCodeService.insert(qRCode);

        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = new Date().getTime() + "qrcode.png";
        File createFile = new File(path+"/"+fileName);

        //访问路径 服务器地址+ findAppUrl + key_id
        String urltxt = tempContextUrl+"findAppUrl/"+key_id;
        log.info("urltxt - {}", urltxt);

        //生成二维码
        String imageBase64QRCode = "";
        if(logoFile != null){
            String logoFileName = logoFile.getOriginalFilename();
            File targetFile = new File(path, logoFileName);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            logoFile.transferTo(targetFile);
            imageBase64QRCode = ZXingCodeUtil.getLogoQRCode(urltxt, request, "", targetFile, createFile);
            //删除上传的logo
            targetFile.delete();
        }else{
            imageBase64QRCode = ZXingCodeUtil.getQRCode(urltxt, request, "", createFile);
        }

        //二维码地址
        String qrcode_path = tempContextUrl+"upload/"+fileName;

        Map data = new HashMap<String, String>();
        data.put("recreateFlag", "0");
        data.put("qrcode_path", qrcode_path);
        data.put("accessKey", "13598992");
        data.put("shortUrl", urltxt);

        return Result.success(data);
    }

    /**
     * url链接或者文本生成二维码
     * @param request
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping("urlQRCode")
    @ResponseBody
    public Object  UrlQRCode(HttpServletRequest request,ModelMap model,
                                 @RequestParam(value="file",required=false) CommonsMultipartFile logoFile,
                                 @RequestParam(value="urltxt",required=false) String urltxt) throws IOException {

        log.info("UrlQRCode - {}", "开始了");
        log.info("页面传递的文本内容- {}", urltxt);

        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getContextPath()).append("/").toString();


        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = new Date().getTime() + "url.png";
        File createFile = new File(path+"/"+fileName);
        //生成二维码
        String imageBase64QRCode = "";
        if(logoFile != null){
            String logoFileName = logoFile.getOriginalFilename();
            File targetFile = new File(path, logoFileName);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            logoFile.transferTo(targetFile);
            imageBase64QRCode = ZXingCodeUtil.getLogoQRCode(urltxt, request, "", targetFile, createFile);
            //删除上传的logo
            targetFile.delete();
        }else{
            imageBase64QRCode = ZXingCodeUtil.getQRCode(urltxt, request, "", createFile);
        }

        //二维码地址
        String qrcode_path = tempContextUrl+"upload/"+fileName;

        Map data = new HashMap<String, String>();
        data.put("qrcode_path", qrcode_path);
        data.put("qrcode", imageBase64QRCode);
        return  Result.success(data);
    }

    /**
     * 二维码下载
     * @param qrcode_path
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/download")
    public void downloadFile(@RequestParam(value="qrcode_path",required=true) String qrcode_path,
                             HttpServletRequest request, HttpServletResponse response) throws IOException {

        String destUrl = qrcode_path;
        // 建立链接
        URL url = new URL(destUrl);
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
        // 连接指定的资源
        httpUrl.connect();
        // 获取网络输入流
        BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());

        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(new Date().getTime()+"url.png","UTF-8"));
        OutputStream out = response.getOutputStream();
        byte[] buf = new byte[1024];
        if (destUrl != null) {
            BufferedInputStream br = bis;
            int len = 0;
            while ((len = br.read(buf)) > 0){
                out.write(buf, 0, len);
            }
            br.close();
        }
        out.flush();
        out.close();
    }


    /**
     * 二维码解析
     * @param request
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping("parseQRCode")
    @ResponseBody
    public Object  ParseQRCode(HttpServletRequest request,ModelMap model,
                                   @RequestParam(value="file",required=false) CommonsMultipartFile logoFile) throws IOException {

        log.info("ParseQRCode - {}", "开始了");

        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getContextPath()).append("/").toString();

        String path = request.getSession().getServletContext().getRealPath("upload");

        String logoFileName = logoFile.getOriginalFilename();
        File targetFile = new File(path, logoFileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        logoFile.transferTo(targetFile);

        String text = ZXingCodeUtil.parseQRCode(targetFile);

        targetFile.delete();

        log.info("解析结果 - {}", text);

        return Result.success(text);
    }


}

class UuidUtil {



    public static void main(String[] args) throws WriterException {
        String uuid = generateShortUuid();
        System.out.println(uuid);
    }

    public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };


    public static String generateShortUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();

    }



}

